<template>
	<div class="dashboard-container">
		<el-row :gutter="20">
			<!-- 统计数据卡片 -->
			<el-col :span="6" v-for="(stat, index) in statistics" :key="index">
				<el-card class="stat-card">
					<div class="stat-title">{{ stat.title }}</div>
					<div class="stat-value">{{ stat.value }}</div>
					<!-- <div v-if="stat.subValue" class="stat-sub-value">
						{{ stat.subValue }}
					</div> -->
				</el-card>
			</el-col>
		</el-row>

		<!-- 物业费收入图表 -->
		<el-card class="chart-card">
			<div class="chart-title">本年度物业费收入</div>
			<div ref="chart" class="chart" style="height: 400px"></div>
		</el-card>
	</div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as echarts from "echarts";
import { getStatistics, getPropertyFeeChart } from "@/api/dashboard";

const statistics = ref([]);
const chart = ref(null);

// 获取统计数据
const fetchStatistics = async () => {
	try {
		const res = await getStatistics();
		statistics.value = [
			{ title: "居民总数", value: res.totalResidents },
			{
				title: "投诉处理",
				value: `${res.complaints.processed}/${res.complaints.total}`,
				// subValue: `处理率：${(
				// 	(res.complaints.processed / res.complaints.total) *
				// 	100
				// ).toFixed(2)}%`,
			},
			{ title: "已举办活动", value: res.totalEvents },
			{
				title: "物业费总收入",
				value: `¥${res.totalPropertyFees.toLocaleString()}`,
			},
		];
	} catch (error) {
		console.error("获取统计数据失败:", error);
	}
};

// 获取物业费图表数据
const fetchPropertyFeeChart = async () => {
	try {
		const res = await getPropertyFeeChart();
		const chartInstance = echarts.init(chart.value);

		const option = {
			tooltip: {
				trigger: "axis",
				formatter: "¥{c}",
			},
			xAxis: {
				type: "category",
				data: res.map((item) => `${item.month}月`),
			},
			yAxis: {
				type: "value",
				axisLabel: {
					formatter: "¥{value}",
				},
			},
			series: [
				{
					data: res.map((item) => item.totalAmount),
					type: "line",
					smooth: true,
					areaStyle: {
						color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
							{ offset: 0, color: "rgba(64, 158, 255, 0.6)" },
							{ offset: 1, color: "rgba(64, 158, 255, 0.1)" },
						]),
					},
					itemStyle: {
						color: "#409EFF",
					},
				},
			],
		};

		chartInstance.setOption(option);

		// 窗口大小变化时调整图表
		window.addEventListener("resize", () => {
			chartInstance.resize();
		});
	} catch (error) {
		console.error("获取物业费图表数据失败:", error);
	}
};

onMounted(() => {
	fetchStatistics();
	fetchPropertyFeeChart();
});
</script>

<style scoped>
.dashboard-container {
	padding: 20px;
}

.stat-card {
	margin-bottom: 20px;
	text-align: center;
}

.stat-title {
	font-size: 16px;
	color: #666;
	margin-bottom: 10px;
}

.stat-value {
	font-size: 24px;
	font-weight: bold;
	color: #333;
}

.stat-sub-value {
	font-size: 14px;
	color: #999;
	margin-top: 5px;
}

.chart-card {
	margin-top: 20px;
}

.chart-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 20px;
}
</style>
